package cn.com.demo.cert;

import cn.com.demo.util.Utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Collection;

public class CertificateFactoryExample {

    /**
     * @param args
     * @throws NoSuchProviderException
     * @throws CertificateException
     * @throws IOException
     * @throws SignatureException
     * @throws SecurityException
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     */
    @SuppressWarnings("unchecked")
    public static void main(String[] args) throws CertificateException, NoSuchProviderException, InvalidKeyException, SecurityException, SignatureException, IOException, NoSuchAlgorithmException {
        KeyPair keyPair = Utils.generateRSAKeyPair(1024);

        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        bOut.write(X509CertificateExample.generateV1Certificate("CN=ROOT", "CN=ROOT", keyPair.getPublic(), keyPair.getPrivate(), "SHA256WithRSAEncryption").getEncoded());
        bOut.write(X509CertificateExample.generateV3Certificate("CN=ROOT", "CN=ROOT", keyPair.getPublic(), keyPair.getPrivate(), "SHA256WithRSAEncryption").getEncoded());
        bOut.close();

        ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray());
		
		/*CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
		X509Certificate cert = (X509Certificate) cf.generateCertificate(bIn);
		System.out.println("issuer : " + cert.getIssuerX500Principal());*/

        CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
        Collection<X509Certificate> certs = (Collection<X509Certificate>) cf.generateCertificates(bIn);
        for (X509Certificate x509Certificate : certs) {
            System.out.println(x509Certificate.getVersion());
        }
    }

}
